package com.jymf.system.controller;

import com.jymf.common.*;
import com.jymf.model.*;
import com.jymf.system.service.CommSystemService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zyj
 * @create 2017-06-05
 **/
@Controller
@RequestMapping("/system")
public class CommSystemController extends HttpJsonObject {
    Log log = LogFactory.getLog(CommSystemController.class);
    @Autowired
    private CommSystemService systemService;
    JsonConfig config = new JsonConfig();

    /**
     * 获取父节点下的子节点
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/getNode", method = RequestMethod.POST)
    public void getNode(HttpServletResponse response, HttpServletRequest request)throws Exception{
        String id = request.getParameter("id");
        if(id==null||id.equals("")){
            id = "1";
        }
        List<TreeVo> childrenTree = systemService.getChildrenTree(id);
        this.outJsonArray(childrenTree, response);
    }

    /**
     * 新增node
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/addNode", method = RequestMethod.POST)
    public void addNode(HttpServletResponse response, HttpServletRequest request)throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("parentId", request.getParameter("id"));
        map.put("name", request.getParameter("name"));
        map.put("code", request.getParameter("code"));
        map.put("icon", request.getParameter("icon"));
        map.put("url", request.getParameter("url"));
        map.put("sort", request.getParameter("sort"));
        map.put("type", request.getParameter("type"));
        map.put("status", request.getParameter("status"));
        map.put("description", request.getParameter("description"));

        boolean b = systemService.saveNode(map);
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("value", b);
        this.outJson(jsonObj, response);
    }

    /**
     * 获取资源信息
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/getResource", method = RequestMethod.POST)
    public void getResource(HttpServletResponse response, HttpServletRequest request)throws Exception{
        String id = request.getParameter("id");

        Resource resource = systemService.getResourceById(Integer.parseInt(id));
        this.outJson(resource, response);
    }

    /**
     * 修改节点
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/editNode", method = RequestMethod.POST)
    public void editNode(HttpServletResponse response, HttpServletRequest request)throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", request.getParameter("id"));
        map.put("name", request.getParameter("name"));
        map.put("code", request.getParameter("code"));
        map.put("icon", request.getParameter("icon"));
        map.put("url", request.getParameter("url"));
        map.put("sort", request.getParameter("sort"));
        map.put("type", request.getParameter("type"));
        map.put("status", request.getParameter("status"));
        map.put("description", request.getParameter("description"));

        boolean b = systemService.editNode(map);
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("value", b);
        this.outJson(jsonObj, response);
    }

    /**
     * 删除数据
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/deleteNode", method = RequestMethod.POST)
    public void deleteNode(HttpServletResponse response, HttpServletRequest request)throws Exception{
        String id = request.getParameter("id");

        boolean b = systemService.deleteNode(Integer.parseInt(id));
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("value", b);
        this.outJson(jsonObj, response);
    }


    /**
     * 获取角色列表
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/roleList",method = RequestMethod.POST)
    public void roleList(HttpServletResponse response, HttpServletRequest request)throws Exception{
        Users user = SessionUtil.getSession(request);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", request.getParameter("name"));
        map.put("code", user.getLgname());
        Page<Role> page = new Page<Role>();
        page.setPageNo( Integer.parseInt(request.getParameter("pageNumber")));
        page.setPageSize(Integer.parseInt(request.getParameter("pageSize")));
        page.setParams(map);
        List<Role> listArticle = systemService.getRolePageInfo(page);
        page.setRows(listArticle);

        this.outJson(page,response);
    }

    /**
     * 保存角色
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/saveRole", method = RequestMethod.POST)
    public void saveRole(HttpServletResponse response, HttpServletRequest request)throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", request.getParameter("name"));
        map.put("code", request.getParameter("code"));
        map.put("status", request.getParameter("status"));
        map.put("description", request.getParameter("description"));

        boolean b = systemService.saveRole(map);
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("value", b);
        this.outJson(jsonObj, response);
    }

    /**
     * 修改角色
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/editRole", method = RequestMethod.POST)
    public void editRole(HttpServletResponse response, HttpServletRequest request)throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", request.getParameter("id"));
        map.put("name", request.getParameter("name"));
        map.put("code", request.getParameter("code"));
        map.put("status", request.getParameter("status"));
        map.put("description", request.getParameter("description"));

        boolean b = systemService.editRole(map);
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("value", b);
        this.outJson(jsonObj, response);
    }

    /**
     * 获取资源
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/getResourceList", method = RequestMethod.POST)
    public void getResourceList(HttpServletResponse response, HttpServletRequest request) throws Exception{
        Users users  = SessionUtil.getSession(request);
        List<TreeVo> resource = systemService.getResource(users.getLgname());

        this.outJsonArray(resource,response);
    }


    /**
     * 添加资源权限
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/editRoleSource", method = RequestMethod.POST)
    public void editRoleSource(HttpServletResponse response, HttpServletRequest request) throws Exception{
        Map<String, Object> parMap = new HashMap<String, Object>();
        parMap.put("roleid", request.getParameter("roleID"));
        parMap.put("sourceid", request.getParameter("res"));
        boolean b = false;
        try {
            systemService.editRoleResource(parMap);
            b = true;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e);
        }

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("value", b);
        this.outJson(jsonObj, response);
    }

    /**
     * 添加资源权限
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/getRoleSource", method = RequestMethod.POST)
    public void getRoleSource(HttpServletResponse response, HttpServletRequest request) throws Exception{
        String roleID = request.getParameter("roleID");

        List<Rolesource> list = systemService.getRoleSource(roleID);
        this.outJsonArray(list, response);
    }

    /**
     * 删除角色
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/deleteRole", method = RequestMethod.POST)
    public void deleteRole(HttpServletResponse response, HttpServletRequest request) throws Exception{
        String roleid = request.getParameter("roleid");
        boolean b = false;
        try{
            systemService.deleteRole(roleid);
            b = true;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e);
        }

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("value", b);
        this.outJson(jsonObj, response);
    }

    /**
     * 获取角色列表
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/userList",method = RequestMethod.POST)
    public void userList(HttpServletResponse response, HttpServletRequest request)throws Exception{
       /* Map<String, Object> map = CommonUtils.getLimit(Integer.parseInt(request.getParameter("pageSize")),
                Integer.parseInt(request.getParameter("pageNumber")));
        map.put("usrName", request.getParameter("usrName"));
        config.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
        Map<String, Object> article = systemService.getUserPage(map);

        JSONObject jsonValue = new JSONObject();
        jsonValue.put("total", article.get("total"));
        jsonValue.put("rows", JSONArray.fromObject(article.get("info"),config));*/

        Users user = SessionUtil.getSession(request);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("usrName", request.getParameter("usrName"));
        map.put("code", user.getLgname());
        Page<Users> page = new Page<Users>();
        page.setPageNo( Integer.parseInt(request.getParameter("pageNumber")));
        page.setPageSize(Integer.parseInt(request.getParameter("pageSize")));
        page.setParams(map);
        List<Users> listArticle = systemService.getUserPageList(page);
        page.setRows(listArticle);

        this.outJson(page,response);
    }

    /**
     * 保存用户
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/saveUsers", method = RequestMethod.POST)
    public void saveUsers(HttpServletResponse response, HttpServletRequest request)throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("lgName", request.getParameter("lgName"));
        map.put("usrName", request.getParameter("usrName"));
        map.put("usrPhone", request.getParameter("usrPhone"));
        map.put("description", request.getParameter("description"));
        map.put("usrStatus", request.getParameter("usrStatus"));
        map.put("lgPasswd", MD5.EncoderPwdByMd5(ConfigValue.getValue("lgPasswd")));

        boolean b = systemService.saveUsers(map);
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("value", b);
        this.outJson(jsonObj, response);
    }

    /**
     * 修改用户
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/editUsers", method = RequestMethod.POST)
    public void editUsers(HttpServletResponse response, HttpServletRequest request)throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("lgName", request.getParameter("lgName"));
        map.put("usrName", request.getParameter("usrName"));
        map.put("usrPhone", request.getParameter("usrPhone"));
        map.put("description", request.getParameter("description"));
        map.put("usrStatus", request.getParameter("usrStatus"));
        map.put("id", request.getParameter("id"));

        boolean b = systemService.editUsers(map);
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("value", b);
        this.outJson(jsonObj, response);
    }

    /**
     * 获取用户信息
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    public void getUserInfo(HttpServletResponse response, HttpServletRequest request)throws Exception{
        String id = request.getParameter("id");
        JSONObject jsonObj = new JSONObject();
        Users user = systemService.getUserInfo(id);
        if(user==null||user.getLgname()==null||user.getLgname().equals("")){
            jsonObj.put("value",false);
        }else {
            jsonObj.put("value",true);
            jsonObj.put("message",user);
        }
        this.outJson(jsonObj, response);
    }

    @RequestMapping(value = "/getUserRolesList", method = RequestMethod.POST)
    public void getUserRolesList(HttpServletResponse response, HttpServletRequest request)throws Exception{
        Users users = SessionUtil.getSession(request);
        List<Map<String, Object>> userRolesList = systemService.getUserRolesList(users.getLgname());
        this.outJsonArray(userRolesList, response);
    }

    /**
     * 获取用户
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/getUserRoleInfo", method = RequestMethod.POST)
    public void getUserRoleInfo(HttpServletResponse response, HttpServletRequest request)throws Exception{
        String id = request.getParameter("userId");
        List<Integer> userRolesList = systemService.getUserRoleInfo(id);
        this.outJsonArray(userRolesList, response);
    }

    /**
     * 修改用户角色
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/editUserRoles", method = RequestMethod.POST)
    public void editUserRoles(HttpServletResponse response, HttpServletRequest request)throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId",request.getParameter("userId"));
        map.put("roleIds",request.getParameter("roleIds"));
        boolean b = false;

        try {
            systemService.editUserRoles(map);
            b = true;
        } catch (Exception e){
            e.printStackTrace();
            log.error(e);
        }

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("value", b);
        this.outJson(jsonObj, response);
    }

    /**
     * 删除用户
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/deleteUsers", method = RequestMethod.POST)
    public void deleteUsers(HttpServletResponse response, HttpServletRequest request)throws Exception{
        boolean b = false;
        try {
            systemService.deleteUsers(request.getParameter("userId"));
            b = true;
        } catch (Exception e){
            e.printStackTrace();
            log.error(e);
        }

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("value", b);
        this.outJson(jsonObj, response);
    }


    /**
     * 修改密码
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value="/editPasswd",method = RequestMethod.POST)
    public void editPasswd(HttpServletResponse response, HttpServletRequest request) throws Exception {
        JSONObject json = new JSONObject();
        try {
            systemService.editPasswd(request.getParameter("id"));
            json.put("value", true);
        } catch (Exception e){
            e.printStackTrace();
            json.put("value", false);
        }

        this.outJson(json, response);
    }

    /**
     * 获取数据字典
     * @throws Exception
     */
    @RequestMapping(value="/getDictTree",method = RequestMethod.POST)
    public void getDictTree(HttpServletResponse response, HttpServletRequest request)throws Exception{
        this.outJsonArray(systemService.getdictTree(),response);
    }

    /**
     * 获取字典类型
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value="/getDictList",method = RequestMethod.POST)
    public void getDictList(HttpServletResponse response, HttpServletRequest request)throws Exception{

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("codeValue", request.getParameter("codeValue"));
        Page<Map<String, Object>> page = new Page<Map<String, Object>>();
        page.setPageNo( Integer.parseInt(request.getParameter("pageNumber")));
        page.setPageSize(Integer.parseInt(request.getParameter("pageSize")));
        page.setParams(map);
        List<Map<String, Object>> dictList = systemService.getDictList(page);
        page.setRows(dictList);
        this.outJson(page, response);
    }

    /**
     * 获取字典
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value="/getDictDataList",method = RequestMethod.POST)
    public void getDictDataList(HttpServletResponse response, HttpServletRequest request)throws Exception{

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("codeValue", request.getParameter("codeValue"));
        map.put("dictValue", request.getParameter("dictValue"));
        Page<Map<String, Object>> page = new Page<Map<String, Object>>();
        page.setPageNo( Integer.parseInt(request.getParameter("pageNumber")));
        page.setPageSize(Integer.parseInt(request.getParameter("pageSize")));
        page.setParams(map);
        List<Map<String, Object>> dictList = systemService.getDictDataList(page);
        page.setRows(dictList);
        this.outJson(page, response);
    }

    @RequestMapping(value="/addDict",method = RequestMethod.POST)
    public void addDict(HttpServletResponse response, HttpServletRequest request) throws Exception{
        Dictionary dictionary = new Dictionary();
        String dictName = request.getParameter("dictName");
        String dictValue = request.getParameter("dictValue");
        Map<String, Object> result = new HashMap<String, Object>();
        boolean b = false;

        if(dictName==null||dictName.equals("")||dictValue==null||dictValue.equals("")){
            result.put("type", false);
            result.put("info", "数据为空");
            this.outJson(result, response);
            return;
        }

        dictionary.setDictName(dictName);
        dictionary.setDictValue(dictValue);
        try{
            systemService.insertDictionary(dictionary);
            b = true;
            result.put("info", "保存成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            result.put("info", "保存失败");
        }
        result.put("type", b);
        this.outJson(result, response);
    }

    /**
     * 保存字典数据
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value="/addDictData",method = RequestMethod.POST)
    public void addDictData(HttpServletResponse response, HttpServletRequest request) throws Exception{
        Dictionarydata dictionary = new Dictionarydata();
        String dictDataName = request.getParameter("dictDataName");
        String dictDataValue = request.getParameter("dictDataValue");
        String dictValue = request.getParameter("dictValue");
        String isUse = request.getParameter("isUse");
        Map<String, Object> result = new HashMap<String, Object>();
        boolean b = false;

        if(dictDataName==null||dictDataName.equals("")||dictValue==null||dictValue.equals("")
                ||dictDataValue==null||dictDataValue.equals("")){
            result.put("type", false);
            result.put("info", "数据为空");
            this.outJson(result, response);
            return;
        }

        dictionary.setDictdataName(dictDataName);
        dictionary.setDictdataValue(dictDataValue);
        dictionary.setDictValue(dictValue);
        dictionary.setIsUse(Short.parseShort(isUse));
        try{
            systemService.inserDictionaryData(dictionary);
            b = true;
            result.put("info", "保存成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            result.put("info", "保存失败");
        }
        result.put("type", b);
        this.outJson(result, response);
    }

    @RequestMapping(value="/getDictData",method = RequestMethod.POST)
    public void getDictData(HttpServletResponse response, HttpServletRequest request) throws Exception{
        String id = request.getParameter("id");
        Map<String, Object> result = new HashMap<String, Object>();
        boolean b = false;

        Dictionarydata dictDataById = systemService.getDictDataById(Integer.parseInt(id));
        b = true;
        result.put("info", dictDataById);
        result.put("type", b);
        this.outJson(result, response);
    }

    @RequestMapping(value="/editDictData",method = RequestMethod.POST)
    public void editDictData(HttpServletResponse response, HttpServletRequest request){
        Dictionarydata dictionary = new Dictionarydata();
        String dictDataName = request.getParameter("dictDataName");
        String dictDataValue = request.getParameter("dictDataValue");
        String id = request.getParameter("id");
        String isUse = request.getParameter("isUse");
        Map<String, Object> result = new HashMap<String, Object>();
        boolean b = false;

        if(dictDataName==null||dictDataName.equals("")){
            result.put("type", false);
            result.put("info", "数据为空");
            this.outJson(result, response);
            return;
        }

        dictionary.setDictdataName(dictDataName);
        dictionary.setDictdataValue(dictDataValue);
        dictionary.setDataId(Integer.parseInt(id));
        dictionary.setIsUse(Short.parseShort(isUse));
        try{
            systemService.updateDictData(dictionary);
            b = true;
            result.put("info", "修改成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            result.put("info", "修改失败");
        }
        result.put("type", b);
        this.outJson(result, response);
    }

    @RequestMapping(value="/getDictValue",method = RequestMethod.POST)
    public void getDictValue(HttpServletResponse response, HttpServletRequest request){
        String dict = request.getParameter("dictValue");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        boolean b = false;

        if(CommonUtils.isEmpty(dict)){
            resultMap.put("info", "数据为空");
        }else {
            List<Dictionarydata> list = systemService.queryDataByDict(dict);
            resultMap.put("info", list);
            b = true;
        }
        resultMap.put("type", b);
        this.outJson(resultMap, response);
    }

}
